<template>
  <view>
    <Navbar
      title="AI画图"
      :height="Number(height)"
      :boundingTop="Number(boundingTop)"
    ></Navbar>
    <view class="img-content" :style="{ marginTop: 15 + 'px' }">
      <view class="img-content-box" v-if="itemList <= 0">
        <zero-loading type="eyes" position="absolute"></zero-loading>
        <img
          style="width: 100%; height: 100%"
          src="https://ai.mojudianzisw.com/static/img/shop/ai/mhbg.png"
          alt=""
        />
      </view>

      <view class="img-content-box" v-else>
        <img
          style="width: 100%; height: 100%"
          :src="`https://ai2.mojudianzisw.com/img/${itemList[0].path}`"
          alt=""
        />
      </view>

      <view class="img-content-button" v-if="itemList.length <= 0">
        图片生成中(0/1)...
      </view>

      <view
        class="img-content-button"
        v-if="itemList.length > 0"
        @click="$goBack(1)"
      >
        再次生成
      </view>
      <!-- @click="show = true" -->

      <view
        class="img-content-button1"
        v-if="itemList.length > 0"
        @click="downloadImage"
      >
        下载至相册
      </view>

      <view
        class="img-content-button2"
        v-if="itemList.length > 0"
        @click="navigateToWeixin"
      >
        跳转至T恤打印
      </view>
    </view>
    <u-popup :show="show" :round="10" mode="center" @close="close" @open="open">
      <view class="popup-content">
        <view class="popup-content-img">
          <img
            style="width: 460rpx; height: 314rpx"
            src="https://ai.mojudianzisw.com/static/img/shop/ai/zfbg.png"
            alt=""
          />
        </view>
        <view class="popup-content-text"> 支付成功即可开始绘图 </view>
        <view class="popup-content-button" @click="payWechat">立即支付</view>
        <!--payWechat  -->
        <view class="popup-content-nopay" @click="close">暂不支付</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import setMarginTop from "@/mixins/setMarginTop"; // 引入 mixin
import Navbar from "@/components/navbar.vue";
import { fusionImg, task } from "@/api/index.js"; // 引入 api
import { createOrder } from "@/api/index.js"; // 引入 api
// fusionImg
export default {
  mixins: [setMarginTop], // 使用 mixin
  components: {
    Navbar,
  },
  data() {
    return {
      itemList: [],
      show: false,
      prompt: "桂林的山，北海的海。",
      intervalId: null,
    };
  },
  onLoad(options) {
    if (options.value) {
      console.log(options.value);
      this.prompt = options.value;
    }
    this.fusionImgApi();
  },
  onUnload() {
    // 在页面卸载时清除定时器
    if (this.intervalId) {
      clearInterval(this.intervalId);
      console.log("定时器已清除");
    }
  },
  methods: {
    navigateToWeixin() {
      uni.navigateToMiniProgram({
        appId: "wx629579ec2f3cb8d4", // 目标小程序的 appId
        path: "pages/mall/machineDetail?machine_id=100179", // 目标小程序的页面路径
        extraData: {
          from: "uniApp",
        },
        success(res) {
          console.log("成功跳转到目标小程序", res);
        },
        fail(err) {
          console.error("跳转失败", err);
        },
      });
    },
    // `https://ai2.mojudianzisw.com/img/${this.itemList[0].path}`
    async downloadImage() {
      uni.showLoading({
        title: "下载中...",
        mask: true,
      });
      // 下载图片
      uni.downloadFile({
        url: `https://ai2.mojudianzisw.com/img/${this.itemList[0].path}`, // 网络图片的 URL
        success: (downloadRes) => {
          if (downloadRes.statusCode === 200) {
            uni.hideLoading();
            // 下载成功后保存图片
            uni.saveImageToPhotosAlbum({
              filePath: downloadRes.tempFilePath,
              success: () => {
                uni.showToast({
                  title: "图片保存成功",
                  icon: "success",
                });
              },
              fail: (err) => {
                uni.showToast({
                  title: "保存失败",
                  icon: "none",
                });
                console.error("保存图片失败:", err);
              },
            });
          } else {
            uni.showToast({
              title: "下载失败",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: "下载失败",
            icon: "none",
          });
          console.error("下载图片失败:", err);
        },
      });
    },
    close() {
      this.show = false;
    },
    open() {
      this.show = true;
    },
    // 生成图片
    async fusionImgApi() {
      const data = await fusionImg({
        openId: uni.getStorageSync("openId"),
        type: "TEXT",
        prompt: this.prompt,
      });
      console.log(data);
      if (data.code == 200) {
        const taskId = data.info.taskId;

        this.intervalId = setInterval(async () => {
          const res = await task({ taskId: taskId });
          console.log(res);

          if (res.code == 200 && res.info.list.length > 0) {
            console.log("Task completed!");
            this.itemList = res.info.list;
            clearInterval(this.intervalId);
          }
        }, 8000); // 15000ms = 15 秒
        // const res = await task({
        //   taskId: data.info.taskId
        // });
        // console.log(res)
      }
    },
    // 支付
    async payWechat() {
      const data = await createOrder({
        // openId: uni.getStorageSync("openId"),
        orderType: "TEXT",
      });
      console.log(data);
      if (data.code == 200) {
        const that = this;
        uni.requestPayment({
          provider: "wxpay", // 支付宝 provider 使用 wxpay
          timeStamp: data.info.timeStamp, // 时间戳
          nonceStr: data.info.nonceStr, // 随机字符串
          package: data.info.packageVal, // 预支付交易会话标识
          signType: data.info.signType, // 签名方式
          paySign: data.info.paySign, // 签名
          success(res) {
            console.log("支付成功:", res);
            uni.showToast({
              title: "支付成功",
              icon: "success",
            });
            that.itemList = [];
            that.show = false;
            that.fusionImgApi();
            // uni.navigateTo({
            //   url: "/pages/aiimage/createimg",
            // });
          },
          fail(err) {
            console.error("支付失败:", err);
            uni.showToast({
              title: "支付失败",
              icon: "none",
            });
          },
        });

        uni.setStorageSync("timeStamp", data.info.timeStamp);
        uni.setStorageSync("nonceStr", data.info.nonceStr);
        uni.setStorageSync("packageVal", data.info.packageVal);
        uni.setStorageSync("signType", data.info.signType);
        uni.setStorageSync("paySign", data.info.paySign);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.img-content {
  width: 100%;
  min-height: 500rpx;
  height: auto;
  //   border: 1px solid black;
  position: absolute;
  //   display: flex;
  //   justify-content: center;
  &-box {
    width: calc(100% - 120rpx);
    height: 660rpx;
    // border: 1px solid black;
    background: rgba(118, 118, 118, 0.1); /* 背景颜色可以是半透明的 */
    backdrop-filter: blur(10px); /* 设置模糊效果 */
    -webkit-backdrop-filter: blur(10px); /* Safari 支持的前缀 */
    border-radius: 10rpx; /* 可以根据需要调整圆角 */
    margin-top: 110rpx;
    margin-left: 60rpx;
  }
  &-button {
    width: calc(100% - 64rpx);
    height: 88rpx;
    background: #f56364;
    box-shadow: inset 0rpx 8rpx 12rpx 0rpx #ffafb0;
    border-radius: 72rpx;
    text-align: center;
    line-height: 88rpx;
    color: #fff;
    margin-top: 258rpx;
    font-weight: 500;
    font-size: 28rpx;
    margin-left: 32rpx;
  }
  &-button1 {
    width: calc(100% - 64rpx);
    height: 88rpx;
    border-radius: 72rpx;
    border: 2rpx solid #f56364;
    text-align: center;
    line-height: 88rpx;
    color: #f56364;
    margin-top: 32rpx;
    font-weight: 500;
    font-size: 28rpx;
    margin-left: 32rpx;
  }
  &-button2 {
    width: calc(100% - 64rpx);
    height: 88rpx;
    border-radius: 72rpx;
    border: 2rpx solid #f56364;
    text-align: center;
    line-height: 88rpx;
    color: #f56364;
    margin-top: 28rpx;
    font-weight: 500;
    font-size: 32rpx;
    margin-left: 32rpx;
  }
}

.popup-content {
  width: 586rpx;
  min-height: 638rpx;
  &-img {
    width: 100%;
    height: 314rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 50rpx;
  }
  &-text {
    width: 100%;
    display: flex;
    justify-content: center;
    color: #333333;
    font-size: 32rpx;
    font-weight: 400;
    margin-top: 28rpx;
  }
  &-button {
    width: calc(100% - 72rpx);
    height: 90rpx;
    border-radius: 180rpx;
    background: #f56364;
    box-shadow: inset 0rpx 8rpx 12rpx 0rpx #ffafb0;
    text-align: center;
    line-height: 90rpx;
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
    margin: 0 36rpx;
    margin-top: 54rpx;
  }
  &-nopay {
    width: 100%;
    text-align: center;
    font-weight: 500;
    font-size: 32rpx;
    color: #f56364;
    margin-top: 38rpx;
    padding-bottom: 20rpx;
  }
}
</style>
